package com.martin.dms.services.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

import com.martin.dms.dataservices.CategoryDataService;
import com.martin.dms.factories.CategoryFactory;
import com.martin.dms.model.Category;
import com.martin.dms.model.Item;
import com.martin.dms.services.CategoryService;

/**
 * Implementation of the <code>CategoryService</code>.
 * 
 * @author mtsvetkov
 */
public class CategoryServiceImpl implements CategoryService {

    private CategoryDataService categoryDataService;

    private CategoryFactory categoryFactory;

    /**
     * Constructor.
     * 
     * @param categoryDataService - data service for the category entity.
     * @param categoryFactory - factory that creates categories.
     */
    public CategoryServiceImpl(CategoryDataService categoryDataService, CategoryFactory categoryFactory) {
        this.categoryDataService = categoryDataService;
        this.categoryFactory = categoryFactory;
    }

    /**
     * {@inheritDoc}
     */
    public List<Category> getAll() {
        return categoryDataService.getAll();
    }

    /**
     * {@inheritDoc}
     */
    public Category get(long id) {
        return categoryDataService.get(id);
    }

    /**
     * {@inheritDoc}
     */
    public void delete(long id) {
        categoryDataService.delete(id);
    }

    /**
     * {@inheritDoc}
     */
    public void update(long id, String name, List<Long> itemIds) {
        Category category = categoryDataService.get(id);
        Set<Item> items = category.getItems();
        List<Long> toRemove = new ArrayList<Long>();
        for (Item item : items) {
            toRemove.add(item.getId());
        }
        categoryDataService.removeItems(id, toRemove);
        categoryDataService.updateName(id, name);
        if (itemIds != null) {
            categoryDataService.addItems(id, itemIds);
        }
    }

    /**
     * {@inheritDoc}
     */
    public void create(String name, List<Long> itemIds) {
        Category category = categoryFactory.create(name);
        category = categoryDataService.create(category);
        if (itemIds != null) {
            categoryDataService.addItems(category.getId(), itemIds);
        }
    }

}
